<template>
  <div class="tab-content">
    <div class="header-section">
      <div class="title-section">
        <h2>全部数据记录</h2>
        <span class="subtitle">查看设备的所有监测数据</span>
      </div>
      <div class="action-section">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="[
            new Date(2000, 1, 1, 0, 0, 0),
            new Date(2000, 1, 1, 23, 59, 59),
          ]"
          @change="handleDateRangeChange"
        />
        <el-select
          v-model="selectedColumns"
          multiple
          collapse-tags
          collapse-tags-tooltip
          placeholder="选择要展示的数据列"
          class="column-select"
          @change="handleColumnSelect"
        >
          <el-option
            v-for="col in allDataColumns"
            :key="col.prop"
            :label="col.label"
            :value="col.prop"
          />
        </el-select>
        <el-button type="primary" @click="fetchAllData" :loading="loadingAllData">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>数据趋势图</span>
          <div class="y-axis-settings">
            <el-popover
              v-if="selectedColumns.length > 0"
              placement="bottom"
              :width="300"
              trigger="click"
            >
              <template #reference>
                <el-button type="primary" link>
                  <el-icon><Setting /></el-icon>Y轴范围设置
                </el-button>
              </template>
              <div class="y-axis-settings-content">
                <div v-for="col in activeColumns" :key="col.prop" class="y-axis-setting-item">
                  <div class="group-title">{{ col.label }} ({{ col.unit }})</div>
                  <div class="range-inputs">
                    <el-input-number
                      v-model="columnSettings[col.prop].yAxisRange.value.min"
                      :step="1"
                      size="small"
                      placeholder="最小值"
                      @change="updateLineChart"
                    />
                    <span class="range-separator">-</span>
                    <el-input-number
                      v-model="columnSettings[col.prop].yAxisRange.value.max"
                      :step="1"
                      size="small"
                      placeholder="最大值"
                      @change="updateLineChart"
                    />
                  </div>
                </div>
              </div>
            </el-popover>
          </div>
        </div>
      </template>
      <div ref="lineChartRef" class="line-chart" v-loading="loadingAllData"></div>
    </el-card>

    <el-card class="data-table-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>数据详情</span>
          <el-button type="success" @click="exportToExcel">
            <el-icon><Download /></el-icon>导出Excel
          </el-button>
        </div>
      </template>
      <el-table
        :data="paginatedTableData"
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa' }"
        border
        stripe
        v-loading="loadingAllData"
      >
        <!-- 时间列单独处理，确保格式化显示 -->
        <el-table-column prop="system_time" label="时间" width="180" fixed="left">
          <template #default="{ row }">
            {{ dayjs(row.system_time).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column
          v-for="col in displayColumns.filter(col => col.prop !== 'system_time')"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :width="col.width"
        >
          <template #default="{ row }">
            <span v-if="row[col.prop] !== undefined && row[col.prop] !== null">
              {{ typeof row[col.prop] === 'number' ? 
                 (String(row[col.prop]).split('.')[1]?.length >= 3 ? 
                  row[col.prop].toFixed(3) : 
                  String(row[col.prop])) : 
                 row[col.prop] }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper" style="margin-top: 20px; text-align: right;">
        <el-pagination
          v-model:current-page="allDataCurrentPage"
          v-model:page-size="allDataPageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="allDataTotal"
          @size-change="handleAllDataSizeChange"
          @current-change="handleAllDataCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Download } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import * as XLSX from 'xlsx'

const props = defineProps({
  currentDevice: {
    type: Object,
    required: true
  }
})

// 全部数据相关
const dateRange = ref([])
const selectedColumns = ref([])
const allDataRecords = ref([])

// 为每个数据列定义Y轴范围
const columnSettings = {
  // 压力数据
  oil_pressure: { unit: 'MPa', yAxisRange: ref({ min: 0, max: 10 }) },
  casing_pressure: { unit: 'MPa', yAxisRange: ref({ min: 0, max: 10 }) },
  c1: { unit: 'MPa', yAxisRange: ref({ min: 0, max: 10 }) },
  c3: { unit: 'MPa', yAxisRange: ref({ min: 0, max: 10 }) },
  
  // 温度数据
  wellhead_temperature: { unit: '°C', yAxisRange: ref({ min: 0, max: 100 }) },
  c2: { unit: '°C', yAxisRange: ref({ min: 0, max: 100 }) },
  // 气流量数据
  c4: { unit: 'm³/h', yAxisRange: ref({ min: 0, max: 1000 }) },
  c5: { unit: 'm³', yAxisRange: ref({ min: 0, max: 10000 }) },

  // 载荷数据
  maximum_load: { unit: 'kN', yAxisRange: ref({ min: 0, max: 200 }) },
  minimum_load: { unit: 'kN', yAxisRange: ref({ min: 0, max: 200 }) },

  // 皮带打滑率
  belt_slip_rate: { unit: '%', yAxisRange: ref({ min: -100, max: 100 }) },

  // 电流数据
  up_maximum_current: { unit: 'A', yAxisRange: ref({ min: 0, max: 120 }) },
  maximum_downgoing_current: { unit: 'A', yAxisRange: ref({ min: 0, max: 120 }) },
  motor_real_time_current: { unit: 'A', yAxisRange: ref({ min: 0, max: 120 }) },

  // 电压数据
  motor_real_time_voltage: { unit: 'V', yAxisRange: ref({ min: 0, max: 500 }) },

  // 功率数据
  real_time_active_power_of_motor: { unit: 'kW', yAxisRange: ref({ min: 0, max: 100 }) },

  // 泵效数据
  real_time_pumping_efficiency: { unit: '%', yAxisRange: ref({ min: 0, max: 100 }) },
  average_pump_efficiency_for_the_day: { unit: '%', yAxisRange: ref({ min: 0, max: 100 }) },

  // 冲程数据
  stroke: { unit: 'm', yAxisRange: ref({ min: 0, max: 10 }) },
  artwork_data_stroke: { unit: 'm', yAxisRange: ref({ min: 0, max: 10 }) },

  // 冲次数据
  jig_frequency: { unit: '次/min', yAxisRange: ref({ min: 0, max: 10 }) },
  artwork_data_jig_frequency: { unit: '次/min', yAxisRange: ref({ min: 0, max: 10 }) },
  variable_frequency_operation_frequency: { unit: '次/min', yAxisRange: ref({ min: 0, max: 10 }) },

  // 能耗数据
  daily_power_consumption: { unit: 'kWh', yAxisRange: ref({ min: 0, max: 1000 }) },
  energy_consumption_per_ton_of_liquid: { unit: 'kWh', yAxisRange: ref({ min: 0, max: 1000 }) },

  // 产量数据
  cumulative_fluid_production_for_the_day: { unit: 't', yAxisRange: ref({ min: 0, max: 1000 }) },

  // 其他数据
  displacement: { unit: '', yAxisRange: ref({ min: 0, max: 100 }) },
  total_number_of_strokes_on_the_day: { unit: '', yAxisRange: ref({ min: 0, max: 100 }) },
  forecasted_liquid_par_value: { unit: '', yAxisRange: ref({ min: 0, max: 100 }) },
  running_time: { unit: '', yAxisRange: ref({ min: 0, max: 100 }) },
  balance_of_counterweight: { unit: '', yAxisRange: ref({ min: 0, max: 100 }) },
  fluid_specific_gravity: { unit: '', yAxisRange: ref({ min: 0, max: 100 }) },
  frequency_conversion_parameter: { unit: '', yAxisRange: ref({ min: 0, max: 100 }) },
  pumping_unit_parameter: { unit: '', yAxisRange: ref({ min: 0, max: 100 }) },
  motor_power_factor: { unit: '', yAxisRange: ref({ min: 0, max: 100 }) }
}

// 定义数据组
const dataGroups = [
  {
    name: '压力数据',
    unit: 'MPa',
    columns: ['oil_pressure', 'casing_pressure', 'c1', 'c3']
  },
  {
    name: '温度数据',
    unit: '°C',
    columns: ['wellhead_temperature', 'c2']
  },
  {
    name: '气流量数据',
    unit: 'm³/h',
    columns: ['c4']
  },
  {
    name: '累计气流量',
    unit: 'm³',
    columns: ['c5']
  },
  {
    name: '载荷数据',
    unit: 'kN',
    columns: ['maximum_load', 'minimum_load']
  },
  {
    name: '电流数据',
    unit: 'A',
    columns: ['up_maximum_current', 'maximum_downgoing_current', 'motor_real_time_current']
  },
  {
    name: '电压数据',
    unit: 'V',
    columns: ['motor_real_time_voltage']
  },
  {
    name: '功率数据',
    unit: 'kW',
    columns: ['real_time_active_power_of_motor']
  },
  {
    name: '泵效数据',
    unit: '%',
    columns: ['real_time_pumping_efficiency', 'average_pump_efficiency_for_the_day']
  },
  {
    name: '冲程数据',
    unit: 'm',
    columns: ['stroke', 'artwork_data_stroke']
  },
  {
    name: '冲次数据',
    unit: '次/min',
    columns: ['jig_frequency', 'artwork_data_jig_frequency', 'variable_frequency_operation_frequency']
  },
  {
    name: '能耗数据',
    unit: 'kWh',
    columns: ['daily_power_consumption', 'energy_consumption_per_ton_of_liquid']
  },
  {
    name: '产量数据',
    unit: 't',
    columns: ['cumulative_fluid_production_for_the_day']
  }
]

// 获取列所属的组
const getColumnGroup = (colProp) => {
  for (const group of dataGroups) {
    if (group.columns.includes(colProp)) {
      return group
    }
  }
  return null
}

const allDataColumns = ref([
  // 基础数据
  //{ prop: 'system_time', label: '系统时间', width: '180' },
  { prop: 'oil_pressure', label: '油压', width: '100' },
  { prop: 'casing_pressure', label: '套压', width: '100' },
  { prop: 'wellhead_temperature', label: '井口温度', width: '100' },
  { prop: 'c1', label: '井下压力', width: '100' },
  { prop: 'c2', label: '井下温度', width: '100' },
  { prop: 'c3', label: '流量计压力', width: '100' },
  { prop: 'c4', label: '瞬时气流量', width: '120' },
  { prop: 'c5', label: '累计气流量', width: '120' },

  //{ prop: 'stroke_time', label: '冲程时间', width: '100' },
 // { prop: 'stroke_displacement', label: '冲程位移', width: '100' },
 // { prop: 'stroke_count', label: '冲程次数', width: '100' },

 // { prop: 'automatic_speed_pump_efficiency_set_value', label: '自动调速泵效设定值', width: '150' },
  //{ prop: 'lower_limit_of_motor_operating_frequency', label: '电机运行频率下限', width: '150' },
 // { prop: 'maximum_allowable_motor_current', label: '允许电机最大电流', width: '150' },
  { prop: 'displacement', label: '位移', width: '100' },
 // { prop: 'power_equipment_start_alarm_delay_time', label: '动力设备启动报警延时时间', width: '180' },
  { prop: 'real_time_pumping_efficiency', label: '实时泵效', width: '100' },
  { prop: 'total_number_of_strokes_on_the_day', label: '当天累计冲次', width: '120' },
  { prop: 'daily_power_consumption', label: '当天耗电量', width: '120' },
  { prop: 'cumulative_fluid_production_for_the_day', label: '当天累计产液量', width: '150' },
  { prop: 'average_pump_efficiency_for_the_day', label: '当天平均泵效', width: '120' },
  { prop: 'energy_consumption_per_ton_of_liquid', label: '吨液能耗', width: '100' },
  { prop: 'forecasted_liquid_par_value', label: '预测液面值', width: '120' },
  { prop: 'maximum_load', label: '最大载荷', width: '100' },
  { prop: 'minimum_load', label: '最小载荷', width: '100' },
  { prop: 'up_maximum_current', label: '上行最大电流', width: '120' },
  { prop: 'maximum_downgoing_current', label: '下行最大电流', width: '120' },
  { prop: 'running_time', label: '运行时长', width: '100' },
  { prop: 'balance_of_counterweight', label: '配重平衡度', width: '120' },
  { prop: 'belt_slip_rate', label: '皮带打滑率', width: '120' },
  { prop: 'fluid_specific_gravity', label: '井液比重', width: '100' },
  { prop: 'frequency_conversion_parameter', label: '变频参数', width: '100' },
  { prop: 'real_time_active_power_of_motor', label: '电机实时有功功率', width: '150' },
  { prop: 'motor_real_time_current', label: '电机实时电流', width: '120' },
  { prop: 'motor_real_time_voltage', label: '电机实时电压', width: '120' },
  { prop: 'pumping_unit_parameter', label: '抽油机参数', width: '120' },
    { prop: 'artwork_data_jig_frequency', label: '实际冲次', width: '100' },
  { prop: 'artwork_data_stroke', label: '实际冲程', width: '100' },
  { prop: 'variable_frequency_operation_frequency', label: '变频运行频率', width: '120' },
  { prop: 'motor_power_factor', label: '电机功率因数', width: '120' },
  { prop: 'jig_frequency', label: '冲次', width: '100' },
  { prop: 'stroke', label: '冲程', width: '100' },
])
const loadingAllData = ref(false)
const allDataCurrentPage = ref(1)
const allDataPageSize = ref(20)
const allDataTotal = ref(0)

// 分页数据计算
const paginatedTableData = computed(() => {
  const start = (allDataCurrentPage.value - 1) * allDataPageSize.value
  const end = start + allDataPageSize.value
  return allDataRecords.value.slice(start, end)
})

// 显示列计算属性
const displayColumns = computed(() => {
  // 如果用户没有选择任何列，则显示所有列
  if (!selectedColumns.value || selectedColumns.value.length === 0) {
    return allDataColumns.value
  }
  // 否则只显示用户选择的列
  return allDataColumns.value.filter(col => selectedColumns.value.includes(col.prop))
})

// 获取全部数据
const fetchAllData = async () => {
  if (!props.currentDevice) {
    ElMessage.warning('请先选择设备')
    return
  }
  
  loadingAllData.value = true
  try {
    const token = localStorage.getItem('token')
    // 使用设备的device_number作为deviceId
    const deviceNumber = props.currentDevice.device_number || props.currentDevice.id.toString()
    if (!deviceNumber) {
      throw new Error('无效的设备ID')
    }

    let url
    if (dateRange.value && dateRange.value.length === 2) {
      // 使用自定义时间范围查询，转换为ISO格式
      const startTime = dayjs(dateRange.value[0]).subtract(8, 'hour').format('YYYY-MM-DDTHH:mm:ss[Z]')
      const endTime = dayjs(dateRange.value[1]).subtract(8, 'hour').format('YYYY-MM-DDTHH:mm:ss[Z]')
      url = `https://penglink.pcwxcn.top/api/oil/data/range/${deviceNumber}?range_type=custom&page=1&page_size=2000&start=${startTime}&end=${endTime}`
    } else {
      // 默认使用today范围类型
      url = `https://penglink.pcwxcn.top/api/oil/data/range/${deviceNumber}?range_type=today&page=1&page_size=2000`
    }

    console.log('请求URL:', url)

    const response = await fetch(url, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error('获取数据失败')
    }

    const result = await response.json()
    console.log('API完整响应:', result)
    
    if (result.code === 200) {
      // 检查API返回的数据结构
      console.log('API返回数据:', result.data)
      
      // 确保数据列表存在并且是数组
      if (result.data) {
        // 检查数据结构 - 有些API可能直接返回数组，有些可能返回包含list的对象
        let dataList = [];
        if (Array.isArray(result.data)) {
          console.log('数据是数组格式');
          dataList = result.data;
          allDataTotal.value = result.data.length || 0;
        } else if (result.data.list && Array.isArray(result.data.list)) {
          console.log('数据包含list数组');
          dataList = result.data.list;
          allDataTotal.value = result.data.total || dataList.length || 0;
        } else if (typeof result.data === 'object') {
          // 尝试将对象转换为数组
          console.log('数据是单个对象格式');
          dataList = [result.data];
          allDataTotal.value = 1;
        }
        
        // 打印原始数据的第一条记录，查看字段结构
        if (dataList.length > 0) {
          console.log('API返回的第一条原始数据:', JSON.stringify(dataList[0], null, 2));
          console.log('API返回的数据字段:', Object.keys(dataList[0]));
        }
        
        // 处理数据，确保所有数值型字段都是数字
        allDataRecords.value = dataList.map(item => {
          const processedItem = {...item};
          
          // 遍历所有可能的数值字段，确保它们是数字类型
          Object.keys(item).forEach(key => {
            const value = item[key];
            if (value !== undefined && value !== null) {
              // 尝试将字符串转换为数字
              if (typeof value === 'string' && !isNaN(Number(value)) && value !== '') {
                processedItem[key] = Number(value);
              }
            }
          });
          
          return processedItem;
        });
        
        // 检查是否有新的字段在当前列定义中不存在
        if (allDataRecords.value.length > 0) {
          const firstRecord = allDataRecords.value[0];
          const existingProps = allDataColumns.value.map(col => col.prop);
          const newFields = Object.keys(firstRecord).filter(key => !existingProps.includes(key));
          
          if (newFields.length > 0) {
            console.log('发现API返回了新字段，但未在列定义中:', newFields);
          }
        }
        
        // 检查第一条数据的结构（如果存在）
        if (allDataRecords.value.length > 0) {
          console.log('处理后的第一条数据:', allDataRecords.value[0]);
          // 检查每个字段的类型
          const firstItem = allDataRecords.value[0];
          console.log('数据字段类型:');
          allDataColumns.value.forEach(col => {
            console.log(`${col.label}(${col.prop}): ${typeof firstItem[col.prop]}`, firstItem[col.prop]);
          });
        } else {
          console.log('API返回的数据列表为空');
          ElMessage.warning('未找到符合条件的数据记录');
        }
      } else {
        console.error('API返回的数据结构不符合预期:', result.data);
        allDataRecords.value = [];
        allDataTotal.value = 0;
        ElMessage.warning('返回的数据格式不正确');
      }
      
      // 如果有选择的列，更新图表
      if (selectedColumns.value.length > 0) {
        nextTick(() => {
          updateLineChart()
        })
      }
    } else {
      throw new Error(result.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据错误:', error)
    ElMessage.error(error.message)
    allDataRecords.value = []
    allDataTotal.value = 0
  } finally {
    loadingAllData.value = false
  }
}

// 处理时间范围变化
const handleDateRangeChange = () => {
  allDataCurrentPage.value = 1
  fetchAllData().then(() => {
    if (selectedColumns.value.length > 0) {
      nextTick(() => {
        updateLineChart()
      })
    }
  })
}

// 处理列选择变更
const handleColumnSelect = () => {
  if (selectedColumns.value.length > 0) {
    nextTick(() => {
      updateLineChart()
    })
  }
}

// 处理页码变更
const handleAllDataSizeChange = (val) => {
  allDataPageSize.value = val
  allDataCurrentPage.value = 1
}

const handleAllDataCurrentChange = (val) => {
  allDataCurrentPage.value = val
}

// 导出Excel功能
const exportToExcel = () => {
  if (!props.currentDevice) {
    ElMessage.warning('请先选择设备')
    return
  }

  if (!allDataRecords.value.length) {
    ElMessage.warning('请先获取数据')
    return
  }

  try {
    // 准备导出数据
    const exportData = allDataRecords.value.map(item => {
      const row = {}
      // 添加时间列
      row['时间'] = dayjs(item.system_time).format('YYYY-MM-DD HH:mm:ss')
      // 添加其他数据列
      allDataColumns.value.forEach(col => {
        row[col.label] = item[col.prop]
      })
      return row
    })

    // 创建工作簿
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.json_to_sheet(exportData)

    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '设备数据')

    // 导出文件
    const fileName = `设备数据_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`
    XLSX.writeFile(wb, fileName)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出Excel失败:', error);
    ElMessage.error('导出失败')
  }
}

// 图表相关
const lineChartRef = ref(null)
let lineChart = null

// 生成随机颜色但保持一定的区分度
const generateColor = (index) => {
  const colors = [
    '#5470c6', '#91cc75', '#fac858', '#ee6666',
    '#73c0de', '#3ba272', '#fc8452', '#9a60b4'
  ]
  return colors[index % colors.length]
}

// 获取列的设置信息
const getColumnSettings = (colProp) => {
  return columnSettings[colProp] || { unit: '', yAxisRange: ref({ min: 0, max: 100 }) }
}

// 获取当前选中的列设置
const activeColumns = computed(() => {
  return selectedColumns.value.map(col => ({
    prop: col,
    label: allDataColumns.value.find(c => c.prop === col)?.label || col,
    ...getColumnSettings(col)
  }))
})

// 更新折线图
const updateLineChart = () => {
  if (!lineChartRef.value) return
  
  if (!lineChart) {
    lineChart = echarts.init(lineChartRef.value)
  }
  
  if (selectedColumns.value.length === 0 || allDataRecords.value.length === 0) {
    lineChart.setOption({
      title: {
        text: '请选择要显示的数据列',
        left: 'center',
        top: 'center',
        textStyle: {
          color: '#999',
          fontSize: 16,
          fontWeight: 'normal'
        }
      }
    })
    return
  }
  
  // 准备数据
  const times = allDataRecords.value
    .map(item => dayjs(item.system_time).format('YYYY-MM-DD HH:mm:ss'))
    .sort((a, b) => dayjs(a).valueOf() - dayjs(b).valueOf())
  const sortedIndices = allDataRecords.value
    .map((item, index) => ({ time: dayjs(item.system_time).valueOf(), index }))
    .sort((a, b) => a.time - b.time)
    .map(item => item.index)

  // 为每个选中的列创建独立的Y轴
  const yAxis = []
  const series = []
  
  selectedColumns.value.forEach((col, index) => {
    const settings = getColumnSettings(col)
    const columnLabel = allDataColumns.value.find(c => c.prop === col)?.label || col
    
    // 创建独立的Y轴
    yAxis.push({
      name: columnLabel + (settings.unit ? `(${settings.unit})` : ''),
      type: 'value',
      position: index % 2 === 0 ? 'left' : 'right',
      offset: Math.floor(index / 2) * 60,
      min: settings.yAxisRange.value.min,
      max: settings.yAxisRange.value.max,
      axisLabel: {
        formatter: settings.unit ? `{value} ${settings.unit}` : '{value}',
        color: generateColor(index)
      },
      nameTextStyle: {
        color: generateColor(index)
      },
      axisLine: {
        lineStyle: {
          color: generateColor(index)
        }
      }
    })
    
    // 准备系列数据
    series.push({
      name: columnLabel,
      type: 'line',
      yAxisIndex: index,
      data: sortedIndices.map(i => {
        let value = allDataRecords.value[i][col]
        // 对泵效数据进行处理，将小数转换为百分比
        if (col === 'real_time_pumping_efficiency' || col === 'average_pump_efficiency_for_the_day') {
          value = value * 100
        }
        return value
      }),
      showSymbol: false,
      smooth: true,
      lineStyle: {
        color: generateColor(index)
      },
      itemStyle: {
        color: generateColor(index)
      }
    })
  })

  // 设置图表选项
  const option = {
    title: null,
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        let result = dayjs(times[params[0].dataIndex]).format('YYYY-MM-DD HH:mm:ss') + '<br/>'
        params.forEach(param => {
          const group = getColumnGroup(selectedColumns.value[param.seriesIndex])
          const unit = group ? group.unit : ''
          result += `${param.marker}${param.seriesName}: ${param.value?.toFixed(3) || '-'} ${unit}<br/>`
        })
        return result
      }
    },
    legend: {
      data: series.map(s => s.name),
      type: 'scroll',
      bottom: 0
    },
    grid: {
      left: '80',
      right: '80',
      top: '30',
      bottom: '60',
      containLabel: true
    },
    backgroundColor: '#ffffff',
    animation: true,
    xAxis: {
      type: 'category',
      data: times,
      axisLabel: {
        formatter: (value) => dayjs(value).format('HH:mm:ss')
      }
    },
    yAxis,
    series,
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        type: 'slider',
        start: 0,
        end: 100
      }
    ]
  }

  lineChart.setOption(option, true)
}

// 监听数据变化自动更新图表
watch([allDataRecords, dateRange], () => {
  if (selectedColumns.value.length > 0 && lineChart) {
    nextTick(() => {
      try {
        updateLineChart()
      } catch (error) {
        console.error('更新图表时出错:', error)
      }
    })
  }
}, { deep: true })

// 监听设备变化
watch(() => props.currentDevice, (newDevice) => {
  if (newDevice) {
    fetchAllData()
  }
}, { immediate: true })

// 生命周期钩子
onMounted(() => {
  if (props.currentDevice) {
    fetchAllData()
  }
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    if (lineChart) {
      lineChart.resize()
    }
  })
})
</script>

<style scoped>
.tab-content {
  margin-top: 20px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.title-section .subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
  display: block;
}

.action-section {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.chart-card {
  margin-bottom: 16px;
}

.line-chart {
  width: 100%;
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.y-axis-settings-content {
  max-height: 400px;
  overflow-y: auto;
  padding: 8px;
}

.y-axis-setting-item {
  padding: 12px;
  border-bottom: 1px solid #eee;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 8px;
}

.y-axis-setting-item:last-child {
  margin-bottom: 0;
  border-bottom: none;
}

.group-title {
  font-weight: 600;
  margin-bottom: 12px;
  color: #606266;
  font-size: 14px;
}

.range-inputs {
  display: flex;
  align-items: center;
  gap: 8px;
}

.range-separator {
  color: #909399;
}

.data-table-card .card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

:deep(.el-table) {
  --el-table-header-bg-color: #f5f7fa;
  --el-table-border-color: #e4e7ed;
  --el-table-header-text-color: #606266;
}

:deep(.el-table th) {
  font-weight: 600;
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.column-select {
  width: 240px;
}
</style>